<template>
  <rx-dialog @ok="handleSubmit" @cancel="cancel">
    <a-form ref="form" :model="mdl">
      <a-form-item style="display:none">
        <a-input v-model:value="mdl.id"/>
      </a-form-item>
      <a-row>
        <a-col :span="24">
          <a-form-item :label="i18n('form.roleSelection','角色选择')">
            <div class="inputBtnBox" style="width:100%;">
              <span class="rx-groups">
                <a-input class="rx-inputs" v-model:value="roleName" :disabled="true"/>
                <span class="handClose" v-if="!pkId" @click="handRoleClose">
                  <CloseOutlined />
                </span>
              </span>
              <a-button v-if="!pkId" class="btn choice" @click="selectRole">
                {{ $ti18('rxList.select', '选择') }}
              </a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <div class="data-set">
            {{ i18n('form.dataConfiguration', '数据权限配置') }}
          </div>
          <a-collapse class="a-coll-box" v-model:activeKey="activeKey" expand-icon-position="right"
                      @change="typeChange">
            <a-collapse-panel :key="'type_'+dataType.idx" v-for="(dataType,index) in dataTypeList"
                              forceRender>
              <template #header>
                <div class="select-box" @mouseover="dataTypeOver(dataType)"
                     @mouseleave="dataTypeLeave(dataType)">
                  <div class="s-type">
                  <span class="s-type-title">
                    {{ i18n('form.typeSelection', '类型选择') }}:
                  </span>
                    <div class="inputBtnBox">
                    <span class="rx-groups">
                      <a-input class="rx-inputs" v-model:value="dataType.name" :disabled="true"/>
                      <span class="handClose" @click.stop="handClose(dataType)">
                        <CloseOutlined />
                      </span>
                    </span>
                      <a-button class="btn choice" @click.stop="selectDataType(dataType)">
                        {{ $ti18('rxList.select', '选择') }}
                      </a-button>
                    </div>
                  </div>
                  <div class="sqzk">
                    <a-button class="a-btn" v-if="dataType.isBtnShow" type="primary" shape="circle"
                              @click.stop="addType">
                      <PlusOutlined />
                    </a-button>
                    <a-button class="a-btn" danger v-if="dataType.isBtnShow" type="primary" shape="circle"
                              @click.stop="removeType(index)">
                      <DeleteOutlined />
                    </a-button>
                    <span>{{ activeKey == 'type_' + dataType.idx ? $ti18('rxList.putAwayBtn', '收起') : $ti18('rxList.openBtn', '展开') }}</span>
                  </div>
                </div>
              </template>
              <div>
                <div  v-if="dataType.columns.length>0" style="margin-bottom: 6px">
                  <a-button type="primary" @click.stop="addRow(dataType)">
                    {{ $ti18('rxList.add', '新增') }}
                  </a-button>
                  <a-button type="primary" danger @click.stop="removeRow(dataType)" style="margin-left: 6px;">
                    {{ $ti18('rxList.delBtn', '删除') }}
                  </a-button>
                </div>
                <rx-grid
                    :ref="'table_'+dataType.idx"
                    v-if="dataType.columns.length>0"
                    :data="dataType.fields"
                    :field="dataType.idField"
                    :columns="dataType.columns"
                    :selectConfig="{type: 'checkbox'}"
                    :hasPage="false"
                    :treeConfig="{transform:true,rowField: dataType.idField,parentField: 'parentId',hasChild: 'children'}"
                    style="height: 180px;"
                >
                  <template #sn="{row,rowIndex}">
                    <a-input-number :min="1" v-model:value="row.sn" style="width:100%"/>
                  </template>
                  <template #action="{ row, rowIndex }">
                    <RxGridAction :size="2">
                      <div @click.stop="onAddSibling(dataType,row)">
                        {{i18n('form.addSibling','添加同级') }}
                      </div>
                      <div @click.stop="addChildDic(dataType,row)">
                        {{i18n('form.addChild','添加子级') }}
                      </div>
                      <div @click.stop="removeRow(dataType,row)">
                        {{ $ti18('rxList.delBtn', '删除') }}
                      </div>
                    </RxGridAction>
                  </template>
                </rx-grid>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </a-col>
      </a-row>
    </a-form>
  </rx-dialog>
</template>
<script>
import FormEntityDataSettingApi from '@/common/api/form/formEntityDataSetting'
import FormEntityDataTypeApi from "@/common/api/form/formEntityDataType";
import FormBoListApi from "@/common/api/form/formBoList";
import {BaseFormModel, RxDialog, RxGrid, Util} from '@lowcode/jpaas-base-lib';
import DialogBox from "@/assets/js/dialogBox.js";
import {ShareDialog,App} from '@lowcode/jpaas-share-component';

export default {
  name: 'FormEntityDataSettingEdit',
  mixins: [BaseFormModel,App],
  props: {
    parentVm: Function,
  },
  components: {
    RxDialog,
    RxGrid
  },
  data() {
    return {
      activeKey: [],
      dataTypeList: [],
      oriRoleId: "",
      roleId: "",
      roleName: ""
    }
  },
  methods: {
    i18n(name, text, key) {
      return this.$ti18(name, text, "formEntityDataSetting", key);
    },
    async onload_(values) {
      if (!values) {
        var idx = Util.randomId();
        this.activeKey = ['type_' + idx]
        this.dataTypeList = [{idx: idx, fields: [], columns: [], isBtnShow: false}];
      } else {
        this.oriRoleId = values.roleId;
        this.roleId = values.roleId;
        this.roleName = values.roleName;
        if (values.dataTypeId) {
          var self = this;
          var dataTypeIds = values.dataTypeId.split(",");
          var dataTypeNames = values.dataTypeName.split(",");
          for (var i = 0; i < dataTypeIds.length; i++) {
            let dataType = {idx: Util.randomId(), fields: [], columns: [], isBtnShow: false};
            if (i == 0) {
              this.activeKey = ['type_' + dataType.idx];
            }
            dataType.id = dataTypeIds[i];
            dataType.name = dataTypeNames[i];
            let res = await FormEntityDataTypeApi.get(dataTypeIds[i]);
            let data = res.data;
            dataType.idField = data.idField.toUpperCase();
            dataType.textField = data.textField.toUpperCase();
            dataType.dataShowType = data.dataShowType;
            if (values.dataTypeDicMap && values.dataTypeDicMap[dataType.id]) {
              var dicList = values.dataTypeDicMap[dataType.id];
              for (var i = 0; i < dicList.length; i++) {
                var dic = dicList[i];
                var json = {};
                json[dataType.idField] = dic.idValue;
                json[dataType.textField] = dic.textValue;
                json['parentId'] = dic.parentValue;
                json['sn'] = dic.sn;
                dataType.fields.push(json);
              }
            }
            dataType.dialogAlias = data.dialogAlias;
            await self.initColumns(dataType);
            self.dataTypeList.push(dataType);
          }
        }
      }
    },
    get(id) {
      var record = this.parentVm().getSelectRecord();
      return FormEntityDataSettingApi.getByRoleId(record.roleId, record.appId);
    },
    parseDic(dicList, dataType, ary, parentId, path) {
      for (var j = 0; j < ary.length; j++) {
        var dic = {};
        var field = ary[j];
        var idValue = field[dataType.idField]
        dic['idValue'] = idValue;
        dic['textValue'] = field[dataType.textField];
        dic['parentValue'] = parentId;
        dic['path'] = path;
        dic['sn'] = field['sn'];
        if (field.children) {
          this.parseDic(dicList, dataType, field.children, idValue, path + idValue + ".");
        }
        dicList.push(dic);
      }
    },
    validForm(values) {
      if (!this.roleId) {
        this.$message.error(this.i18n('form.configureRoles', '请配置角色！'));
        return false;
      }
      var ary = Util.deepClone(this.dataTypeList);
      for (var i = 0; i < this.dataTypeList.length; i++) {
        var dataType = this.dataTypeList[i];
        if (!dataType.id) {
          ary.splice(i, 1);
        }
      }
      if (ary.length == 0) {
        this.$message.error(this.i18n('form.configureType', '请配置类型！'));
        return false;
      }
      return true;
    },
    save(values) {
      let appId = this.curApp.appId;
      if (appId) {
        values.appId = appId;
      }
      values.roleId = this.roleId;
      values.roleName = this.roleName;
      var dataTypeList = [];
      for (var i = 0; i < this.dataTypeList.length; i++) {
        var dataType = this.dataTypeList[i];
        if (!dataType.id) {
          continue;
        }
        var dicList = [];
        var fields = this.$refs['table_' + dataType.idx][0].getData();
        this.parseDic(dicList, dataType, fields, '0', '0.');
        dataTypeList.push({dataTypeId: dataType.id, dataTypeName: dataType.name, dicList: dicList});
      }
      values.dataTypeList = JSON.stringify(dataTypeList);
      FormEntityDataSettingApi.saveRole(values).then(resp=>{
            Util.closeWindow(this,'ok');
        });
    },
    addData(dataType, callback) {
      if (!dataType.dialogAlias) {
        this.$message.error(this.i18n('form.configureDialog', '请配置对话框!'));
        return;
      }
      var self = this;
      DialogBox.dialog({key: dataType.dialogAlias}, {
        curVm: this
      }, function (action, data) {
        var fields = self.$refs['table_' + dataType.idx][0].getData();
        var ids = [];
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          ids.push(field[dataType.idField]);
        }
        var array = data.rows;
        if (!array) {
          array = data;
        }
        for (var i = 0; i < array.length; i++) {
          var row = array[i];
          if (!ids.includes(row[dataType.idField])) {
            delete row.children;
            if (callback) {
              callback(row);
            }
          }
        }
      });
    },
    addRow(dataType) {
      var table = this.$refs['table_' + dataType.idx][0];
      this.addData(dataType, function (row) {
        table.addRow({...row, sn: 1});
      })
    },
    addChildDic(dataType, record) {
      var table = this.$refs['table_' + dataType.idx][0];
      this.addData(dataType, function (row) {
        table.addRow({...row, sn: 1}, record);
      })
    },
    onAddSibling(dataType, record) {
      var table = this.$refs['table_' + dataType.idx][0];
      this.addData(dataType, function (row) {
        if (record.parentId && record.parentId != '0') {
          var parentNode = table.getParentNode(record);
          table.addRow({...row, sn: 1}, parentNode);
        } else {
          table.addRow({...row, sn: 1});
        }
      })
    },
    removeRow(dataType, record) {
      var table = this.$refs['table_' + dataType.idx][0];
      this.$confirm({
        title: this.$ti18('rxMsa.actionTips', '操作提示'),
        content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
        zIndex: 20000,
        okText: this.$ti18('rxForm.ackBtn', '确认'),
        cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
        onOk() {
          if (record) {
            table.removeRows([record[dataType.idField]]);
          } else {
            table.removeRows();
          }
        }
      })
    },
    dataTypeOver(dataType) {
      dataType.isBtnShow = true;
    },
    dataTypeLeave(dataType) {
      dataType.isBtnShow = false;
    },
    typeChange(key) {
      if (key.length == 0) {
        this.activeKey = [];
        return;
      }
      this.activeKey = [key[key.length - 1]];
    },
    addType() {
      this.dataTypeList.push({idx: Util.randomId(), fields: [], columns: [], isBtnShow: false});
    },
    removeType(index) {
      if (this.dataTypeList.length == 1) {
        this.$message.error(this.i18n('form.notAllowedDeleted', '最后一个不允许删除!'));
        return;
      }
      this.dataTypeList.splice(index, 1);
    },
    handClose(dataType) {
      delete dataType.id;
      delete dataType.name;
    },
    selectDataType(dataType) {
      var config = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
      var self = this;
      ShareDialog.openFormEntityDataTypeDialog(config, function (row) {
        if (self.dataTypeList.filter(item => item.id == row.id).length > 0) {
          self.$message.error(self.i18n('form.beSelected', '已选择此类型!'));
          return;
        }
        dataType.id = row.id;
        dataType.name = row.name;
        dataType.idField = row.idField.toUpperCase();
        dataType.textField = row.textField.toUpperCase();
        dataType.dataShowType = row.dataShowType;
        dataType.dialogAlias = row.dialogAlias;
        self.initColumns(dataType);
      })
    },
    async initColumns(dataType) {
      dataType.columns = [];
      let res = await FormBoListApi.getByKey(dataType.dialogAlias)
      if (res.data.fieldsJson) {
        var fields = JSON.parse(res.data.fieldsJson);
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var fieldName = field.field.toUpperCase();
          if (fieldName == dataType.idField || fieldName == dataType.textField) {
            dataType.columns.push({title: field.header, field: fieldName, treeNode: fieldName == dataType.idField});
          }
        }
        dataType.columns.push({
          title: this.$ti18('rxList.action', '操作'),
          field: 'action',
          slots: {default: 'action'}
        });
      }
    },
    handRoleClose() {
      this.roleId = "";
      this.roleName = "";
    },
    selectRole() {
      var self=this;
      ShareDialog.openGroupDialog({
        curVm: this, data: {single: true, showDimId: false, dimId: '2'}, widthHeight: ['900px', '600px']
      }, function (data) {
        FormEntityDataSettingApi.validRole(data.groupId, self.curApp.appId).then(res => {
          if (res.success || self.oriRoleId == data.groupId) {
            self.roleId = data.groupId;
            self.roleName = data.name;
          } else {
            self.$message.error(self.i18n('form.existsRole', '此角色已存在配置!'));
          }
        })
      })
    }
  }
}
</script>
<style scoped>
.a-coll-box {
  margin: 0px 9px;
}

.sqzk {
  line-height: 36px;
}

.sqzk .a-btn {
  margin-right: 10px;
}

.s-type {
  display: flex;
}

.s-type-title {
  display: inline-block;
  margin-top: 8px;
  margin-right: 10px;
}

.select-box {
  display: flex;
  justify-content: space-between;
}

.data-set {
  border-left: 3px solid #1890fe;
  padding-left: 8px;
  margin-bottom: 10px;
  font-weight: 600;
  margin-left: 10px;
}

.choice {
  background-color: #f5f7fa;
  border-radius: 0px 5px 5px 0px;
  font-weight: normal !important
}

.rx-inputs {
  background-color: white;
}

.rxTagsBox {
  border-right: none;
}

.inputBtnBox {
  display: flex;
  vertical-align: middle;
  flex: 1;
  font-size: 0;
  text-align: left;
  margin-top: 4px;
}

.inputBtnBox .rx-groups {
  flex: 1;
  position: relative;
  width: 100%;
  min-height: 32px;
  line-height: normal;
}

.inputBtnBox .rx-groups .handClose {
  flex: none;
  display: none;
  position: absolute;
  right: 6px;
  text-align: center;
  width: 18px;
  height: 18px;
  line-height: 18px;
  top: 50%;
  margin-top: -9px;
  border-radius: 10px;
  text-align: center;
  background-color: #c0c5cc;
}

.inputBtnBox .btn {
  min-height: 32px !important;
  height: auto !important;
  border: 1px solid #d9d9d9;
  border-left: none;
}
.btn:focus{
  outline: none!important;
}
.inputBtnBox .rx-groups .handClose:hover {
  background-color: #1890ff;
}

.handClose i {
  font-size: 10px;
  color: #fff;
}

.inputBtnBox .rx-groups .rx-inputs {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  width: 100%;
  padding-right: 20px;
  color: #46494d;
}

.inputBtnBox .rx-groups:hover .rx-inputs {
  padding-right: 32px;
}

.inputBtnBox .rx-groups:hover .handClose {
  display: inline-block;
}

.inputBtnBox .rx-groups .handClose i {
  vertical-align: middle;
}

.inputBtnBox .rx-groups .handClose:before {
  content: '';
  display: inline-block;
  height: 100%;
  width: 0;
  vertical-align: middle;
}

.iconButton {
  font-size: 20px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-left: -1px;
}
</style>
